package org.example.template.services;


import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;


//服务端线程类
//继承Thread类的话，必须重写run方法，在run方法中定义需要执行的任务。
@Slf4j
public class ESP8266TcpServerThread extends Thread {
    private Socket socket;

    InputStream inputStream;
    OutputStream outputStream;


    public ESP8266TcpServerThread(Socket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            while (true) {
                //接收客户端的消息并打印
                inputStream = socket.getInputStream();
                byte[] bytes = new byte[100];
                int index=0;
                int indexcalc=0;
                inputStream.read(bytes);

                for (int i = 0; i < bytes.length; i++) {
                    if (bytes[i] != 0) {
                        index++;
                    }
                }
                byte[] result = new byte[index];
                for (int i = 0; i < bytes.length; i++) {
                    if (bytes[i] != 0) {
                        result[indexcalc++]=bytes[i];
                    }
                }

                String string = new String(result,"GBK");
                log.info("接收到的TCP信息为:" + string);

                //TX接受到客户端数据
                //RX发送到客户端数据
                //redisCache.setCacheObject("TCPServer:TXesp8266",string);



                //数据解析
                //String[] array = string.split(",");
                //向客户端返回数据
                //String ver=redisCache.getCacheObject("TCPServer:RXesp8266");
                //if(ver!=null){
                //    outputStream = socket.getOutputStream();
                //    outputStream.write(ver.getBytes());
                //}

            }

        } catch (Exception e) {
            log.error(e.getMessage());
            if(e.getMessage().equals("Software caused connection abort: recv failed")) {
                log.info("客户端主动断开链接");
            }else{
                log.error("报错:"+e);
            }
        }
        //操作结束，关闭socket
        try {
            socket.close();
        } catch (IOException e) {
            log.error("关闭连接出现异常");
            e.printStackTrace();
        }
    }
}
